package sch.guo.crmsys.controller.cop;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.annotations.ApiOperation;
import sch.guo.crmsys.base.ResultUtil;
import sch.guo.crmsys.base.dto.ResultDTO;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import sch.guo.crmsys.dto.cop.ClientDTO;
import sch.guo.crmsys.entity.auth.AuthUser;
import sch.guo.crmsys.service.auth.AuthUserService;
import sch.guo.crmsys.service.cop.CopClientService;
import sch.guo.crmsys.entity.cop.CopClient;

/**
 * @since 2019-12-31
 */
@RestController
@RequestMapping("/copClient")
public class CopClientController {

    @Autowired
    private CopClientService copClientService;
    @Autowired
    private AuthUserService authUserService;

    @PostMapping
    @ApiOperation(value = "插入")
    public ResultDTO insertOne(Authentication authentication,@RequestBody CopClient copClient) throws Exception {
        AuthUser userDetails = authUserService.getUserDetails(authentication);
        copClient.setClientPrincipal(userDetails.getUserId());
        copClientService.save(copClient);
        return ResultUtil.Success(copClient);
    }

    @PutMapping
    @ApiOperation(value = "按ID修改")
    public ResultDTO updateById(@RequestBody CopClient copClient) throws Exception {
        copClientService.updateById(copClient);
        return ResultUtil.Success();
    }

    @DeleteMapping("/{id:\\d+}")
    @ApiOperation("按ID删除")
    public ResultDTO deleteById(@PathVariable Long id) throws Exception {
        copClientService.removeById((long) id);
        return ResultUtil.Success();
    }

    @GetMapping("/list")
    @ApiOperation("查询全部")
    public ResultDTO selectEntityPage(Authentication authentication)throws Exception{

        /*
            查询下属销售人员的编号
         */
        List<AuthUser> userAndChild = authUserService.getUserAndChildId(authentication);
        Set<Long> userId = userAndChild.stream().map(AuthUser::getUserId).collect(Collectors.toSet());
        /*
            查询自己与下属销售人员的客户
         */
        QueryWrapper<CopClient> copClientQueryWrapper = new QueryWrapper<>();
        copClientQueryWrapper.in("client_principal",userId);

        List<CopClient> data = copClientService.list(copClientQueryWrapper);
        int count = data.size();
        return ResultUtil.Success(data,count);
    }

    @GetMapping()
    @ApiOperation("查询、分页返回")
    public ResultDTO selectEntityPage(Authentication authentication,
                                      @RequestParam(value = "page", defaultValue = "0") int pageNum,
                                      @RequestParam(value = "limit", defaultValue = "8") int pageSize,
                                        String clientName)throws Exception{
        /*
            查询下属销售人员的编号
         */
        List<AuthUser> userAndChild = authUserService.getUserAndChildId(authentication);
        Set<Long> userId = userAndChild.stream().map(AuthUser::getUserId).collect(Collectors.toSet());
        /*
            查询自己与下属销售人员的客户
         */
        QueryWrapper<CopClient> copClientQueryWrapper = new QueryWrapper<>();
        copClientQueryWrapper.in("client_principal",userId);
        if (clientName != null && !clientName.isEmpty()) {
            copClientQueryWrapper.like("client_name",clientName);
        }

        IPage<CopClient> page = copClientService.page(new Page<CopClient>(pageNum, pageSize), copClientQueryWrapper);
        List<CopClient> data = page.getRecords();

        /*
            转化为DTO
         */
        List<ClientDTO> clientDTOS = new ArrayList<>();
        for (CopClient client : data) {
            ClientDTO clientDTO = new ClientDTO();
            BeanUtils.copyProperties(client,clientDTO);
            clientDTOS.add(clientDTO);
        }

        for (ClientDTO clientDTO : clientDTOS) {
            for (AuthUser authUser : userAndChild) {
                if (clientDTO.getClientPrincipal().equals(authUser.getUserId())) {
                    clientDTO.setClientPrincipalName(authUser.getUserTrueName());
                }
            }
            int now = LocalDateTime.now().getYear();
            int year = clientDTO.getClientBirthday().getYear();
            clientDTO.setClientAge(LocalDateTime.now().getYear() - clientDTO.getClientBirthday().getYear());
        }

        int count = (int) page.getTotal();
        return ResultUtil.Success(clientDTOS,count);
    }

    @GetMapping("/{id:\\d+}")
    @ApiOperation("ID查询")
    public ResultDTO selectEntityPage(@PathVariable Long id)throws Exception{
        return ResultUtil.Success(copClientService.getById(id));
    }

}
